import React, { useState, useEffect, useCallback } from "react";
import { Form, Input, DatePicker, Button, Layout, List, Row, Col, message, Spin } from 'antd';
import { getCrmRecordById, getCrmRecordFromSql, putdata } from "../../util/util";
import dayjs from 'dayjs'; // 引入 dayjs 来处理日期


const { TextArea } = Input;
const { Sider, Content } = Layout;


const Entitynamemap = {
  "Accounts": { entityname: 'Accounts', showname: "客户", subject: "Account_Name", approvalfieldapiname: "field3" },
  "Sales_Orders": { entityname: 'Sales_Orders', showname: "外销合同", subject: "Subject", approvalfieldapiname: "field2" },
  "PSNotice": { entityname: 'PSNotice', showname: "生产发货通知单", subject: "Name", approvalfieldapiname: "field7" },
  "Stocknotice": { entityname: 'Stocknotice', showname: "备货通知", subject: "Name", approvalfieldapiname: "field" }
};
// 提升为全局变量
let recorddata;
let changtimes;
let approvalfieldapiname;
// const MAX_LENGTH = 32000; // 每个字段的最大长度

const App = (pagedata) => {
  const [form] = Form.useForm();
  const [iscantChange, setIscantChange] = useState(true); // 是否可以修改
  const [initialValues, setInitialValues] = useState({});
  const [listData, setListData] = useState([]);
  const [loading, setLoading] = useState(true); // 加载状态

  let dataid = pagedata?.data?.EntityId[0];
  let Entityname = pagedata?.data?.Entity;

  const fetchData = useCallback(async () => {

    setLoading(true); // 开始加载
    try {
      recorddata = await getCrmRecordById(Entityname, dataid);
      // console.log("recorddata", JSON.stringify(recorddata));
      const eninfo = Entitynamemap[Entityname]
      const code = eninfo?.subject;  // 获取编号字段名

      approvalfieldapiname = eninfo?.approvalfieldapiname;
      let approvalstatus = recorddata[approvalfieldapiname];
      // console.log("approvalstatus", approvalstatus);
      let subject = recorddata[code]; // 获取编号字段的值
      if (approvalstatus === '审批通过' || approvalstatus === "高级副总裁审批通过") {
        setIscantChange(false);
      } else {
        message.success('未走完审批流程的单据无需走变更，如需变更可以撤回审批再修改！');
        // setTimeout(() => {
        //   window.ZOHO.CRM.UI.Popup.close(); // 关闭弹出窗口
        // }, 1000); // 延迟时间，根据需要调整
      }

      if (Entityname === 'Stocknotice') {   //如果已经做过单证就不能修改备货通知
        const sqlstr_dz = `select id from Documentmag where Stocknotice = ${recorddata?.id}`;
        const result_dz = await getCrmRecordFromSql(sqlstr_dz);
        if (result_dz && result_dz._details && result_dz._details.statusMessage && result_dz._details.statusMessage.data && result_dz._details.statusMessage.data.length > 0) {
          message.success('该备货已经做过单证，不能修改！');
          // setTimeout(() => {
          //   window.ZOHO.CRM.UI.Popup.close(); // 关闭弹出窗口
          // }, 500); // 延迟时间，根据需要调整
        }
      }

      // 请求列表数据
      const sql = `select Name,Owner.first_name as Ownername,id,OrderNo,ChangeContent,ChangeReason,ChangeDate,ChangeTimes,ModuleName from ChangeAll where id is not null and Name like '%${subject}%' `;
      const listresult = await getCrmRecordFromSql(sql);
      // console.log("listresult", listresult);
      setListData(listresult); // 更新列表数据
      changtimes = (listresult?.length || 0) + 1;
      const defaultValues = {

        Name: `${subject}-${changtimes}`,
        OrderNo: subject,
        ChangeDate: dayjs(),
        ChangeTimes: changtimes,
        ModuleName: eninfo?.showname,

      };
      setInitialValues(defaultValues);
      form.setFieldsValue(defaultValues);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false); // 完成加载
    }
  }, [dataid, Entityname, form]);


  useEffect(() => {

    const initialize = async () => {
      await window.ZOHO.CRM.UI.Resize({ height: "2000", width: "2000" });
      fetchData();
    };
    initialize();

  }, [fetchData]);

  const newhandleSubmit = async (values) => {
    try {
      setLoading(true); // 开始加载   
      // 创建 Blob 对象，并指定文件类型和编码
      const jsonString = JSON.stringify(recorddata);
      // console.log('jsonString', jsonString);
      const blob = new Blob([jsonString], { type: 'text/plain;charset=utf-8' });
      const file = new File([blob], "recorddata.txt", { type: "text/plain" });

      let config = {
        "CONTENT_TYPE": "multipart",
        "PARTS": [{
          "headers": {
            "Content-Disposition": "file;"
          },
          "content": "__FILE__"
        }],
        "FILE": {
          "fileParam": "files",
          "file": file
        }
      }
      let filerepose = await window.ZOHO.CRM.API.uploadFile(config);
      // console.log("filerepose", JSON.stringify(filerepose));

      if (filerepose && filerepose.data.length > 0) {
        let fid = filerepose.data[0]?.details?.id;


        const formattedValue = {
          ...values,
          ChangeDate: dayjs(values.ChangeDate).format('YYYY-MM-DD'),
          File: [
            {
              "File_Id__s": fid
            }
          ]
        };
        let jsondata = {
          "data": [formattedValue]
        }
        // console.log("jsondata", JSON.stringify(jsondata));
        let req_data = {
          parameters: jsondata,
          headers: {},
          method: "POST",
          url: `https://www.zohoapis.com.cn/crm/v6/ChangeAll`,
          param_type: 2,
        };
        let result = await window.ZOHO.CRM.CONNECTION.invoke("crm", req_data);
        // console.log('result', result);
        if (result && result.details && result.details.statusMessage && result.details.statusMessage.data && result.details.statusMessage.data.length > 0) {
          message.success('提交成功');
          let upinfo = { "data": [{ id: dataid, [approvalfieldapiname]: "待审批", "ChangeTimes": changtimes }] };
          console.log("upinfo", JSON.stringify(upinfo));
          var unlockdata = await putdata(Entityname, upinfo);
          console.log("unlockdata", JSON.stringify(unlockdata));
          setTimeout(() => {
            window.ZOHO.CRM.UI.Popup.closeReload(); // 关闭弹出窗口
          }, 500); // 延迟时间，根据需要调整
        }

      }



    } catch (error) {
      console.error("Error submitting form:", error);
    } finally {
      setLoading(false); // 完成加载
    }

  };

  const handleCancel = () => {
    window.ZOHO.CRM.UI.Popup.close(); // 关闭弹出窗口
  }


  return (
    <>
      <Spin spinning={loading} tip="加载中..." style={{ minHeight: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        <Row justify="end" style={{ marginBottom: 16, padding: '0 20px 0 0' }}>
          <Button style={{ marginRight: 8 }} onClick={handleCancel} >取消</Button>
          <Button type="primary" disabled={iscantChange} onClick={() => form.submit()}>确定</Button>
        </Row>
        <Layout style={{ padding: 20 }}>
          <Sider width={380} style={{ background: '#fff', padding: '10px', marginRight: '8px' }}>
            <Form
              form={form}
              layout="horizontal"
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 16 }}
              onFinish={newhandleSubmit}
              initialValues={initialValues}
            >
              <Form.Item
                label="变更单号"
                name="Name"
                rules={[{ required: true, message: '请输入变更单号' }]}
              >
                <Input disabled />
              </Form.Item>
              <Form.Item
                label="单据号"
                name="OrderNo"
                rules={[{ required: true, message: '请输入单据号' }]}
              >
                <Input disabled />
              </Form.Item>
              <Form.Item
                label="变更日期"
                name="ChangeDate"
                rules={[{ required: true, message: '请选择变更日期' }]}
              >
                <DatePicker style={{ width: '100%' }} disabled />
              </Form.Item>
              <Form.Item
                label="变更次数"
                name="ChangeTimes"
                rules={[{ required: true, message: '请输入变更次数' }]}
              >
                <Input disabled />
              </Form.Item>
              <Form.Item
                label="模块名称"
                name="ModuleName"
                rules={[{ required: true, message: '请输入模块名称' }]}
              >
                <Input disabled />
              </Form.Item>
              <Form.Item
                label="变更原因"
                name="ChangeReason"
                rules={[{ required: true, message: '请输入变更原因' }]}
              >
                <TextArea rows={4} />
              </Form.Item>
              <Form.Item
                label="变更内容"
                name="ChangeContent"
                rules={[{ required: true, message: '请输入变更内容' }]}
              >
                <TextArea rows={4} />
              </Form.Item>
            </Form>
          </Sider>

          <Content style={{ background: '#fff', padding: '10px 10px 10px 10px' }}>
            <List
              header={
                <Row style={{ width: '100%', fontWeight: 'bold', borderBottom: '1px solid #ddd' }}>
                  <Col span={4}>变更单号</Col>
                  <Col span={4}>操作员</Col>
                  <Col span={4}>变更日期</Col>
                  <Col span={6}>变更原因</Col>
                  <Col span={6}>变更内容</Col>
                  {/* <Col span={4}>审核状态</Col> */}
                </Row>
              }
              bordered
              dataSource={listData}
              renderItem={item => (
                <List.Item>
                  <Row style={{ width: '100%' }}>
                    <Col span={4}>{item.Name}</Col>
                    <Col span={4}>{item.Ownername}</Col>
                    <Col span={4}>{item.ChangeDate}</Col>
                    <Col span={6}>{item.ChangeReason}</Col>
                    <Col span={6}>{item.ChangeContent}</Col>
                  </Row>
                </List.Item>
              )}
            />
          </Content>
        </Layout>
      </Spin>
    </>
  );
};

export default App;
